<template>
    <div class="permissions-container">
        <a-spin tip="Loading..." :spinning="loading">
            <a-card title="权限管理">
                <div class="big-box">
                    <a-row>
                        <a-col :span="6" style="margin-top: 19px">
                            <a-tabs type="card" :default-active-key="preType" @change="changeTab">
                                <a-tab-pane tab="组织架构" :key="0">
                                    <div class="left-side">
                                        <a-card title="组织架构">
                                            <a-tree :replace-fields="replaceFields" :tree-data="treeData" @select="onSelect"
                                                v-if="pageReady" :defaultSelectedKeys="[firstOrganizationId]"
                                                :defaultExpandedKeys="[firstOrganizationId]" />
                                        </a-card>
                                    </div>
                                </a-tab-pane>
                                <a-tab-pane tab="员工" :key="1">
                                    <div class="left-side">
                                        <div class="search-box">
                                            <a-input-search v-model="search" style="width: 100%;" allow-clear placeholder="请搜索"
                                                @search="getMemberData"></a-input-search>
                                        </div>
                                        <div class="table-box">
                                            <div class="item" v-for="item in memberList" :key="item.id" :style="{width: '100%'}"
                                                :class="{active:item.userId == selectUser.id}" @click="memberClick(item)">
                                                <a-avatar class="user-avatar" :size="50" :src="item.headPortrait" />
                                                <div class="user-info">
                                                    <div class="name text-nowarp">{{item.name}}</div>
                                                    <div class="type text-nowarp">{{item.organizationName}}</div>
                                                </div>

                                            </div>
                                        </div>
                                    </div>
                                </a-tab-pane>
                            </a-tabs>
                        </a-col>
                        <a-col :span="18">
                            <div class="right-side">
                                <a-row style="margin-top: 20px">
                                    <a-card :title="title">
                                        <div class="list-box"
                                            v-if="(preType===0 && selectNode.id) || (preType===1 && selectUser.id)">
                                            <div class="item-box" v-for="(item,i) in workShopPermission" :key="item.id">
                                                <a-checkbox :checked="resourceIdS.indexOf(item.id)>=0"
                                                    @change="(e)=>checkChange(e,item)">{{item.title}}</a-checkbox>

                                                <a-checkbox :checked="resourceIdS.indexOf(child.id)>=0"
                                                    v-for="(child,index) of item.children" :key="child.id"
                                                    @change="(e)=>checkChange(e,child,item)">{{child.title}}</a-checkbox>
                                            </div>
                                        </div>
                                        <div v-else>请先选择组织架构或员工</div>
                                    </a-card>

                                    <!-- <a-tabs type="card" :default-active-key="0" @change="rightSideChangeTab">
                                        <a-tab-pane tab="工作台" :key="0">
                                            <a-card :title="title">
                                                <div class="list-box"
                                                    v-if="(preType===0 && selectNode.id) || (preType===1 && selectUser.id)">
                                                    <div class="item-box" v-for="(item,i) in workShopPermission" :key="item.id">
                                                        <a-checkbox :checked="resourceIdS.indexOf(item.id)>=0"
                                                            @change="(e)=>checkChange(e,item)">{{item.title}}</a-checkbox>

                                                        <a-checkbox :checked="resourceIdS.indexOf(child.id)>=0"
                                                            v-for="(child,index) of item.children" :key="child.id"
                                                            @change="(e)=>checkChange(e,child,item)">{{child.title}}</a-checkbox>
                                                    </div>
                                                </div>
                                                <div v-else>请先选择组织架构或员工</div>
                                            </a-card>
                                        </a-tab-pane>
                                        <a-tab-pane tab="系统设置" :key="1">
                                            <a-card :title="title">
                                                <div class="list-box"
                                                    v-if="(preType===0 && selectNode.id) || (preType===1 && selectUser.id)">
                                                    <div class="item-box" v-for="(item,i) in settingPermission" :key="item.id">
                                                        <a-checkbox :checked="resourceIdS.indexOf(item.id)>=0"
                                                            @change="(e)=>checkChange(e,item)">{{item.title}}</a-checkbox>

                                                        <a-checkbox :checked="resourceIdS.indexOf(child.id)>=0"
                                                            v-for="(child,index) of item.children" :key="child.id"
                                                            @change="(e)=>checkChange(e,child,item)">{{child.title}}</a-checkbox>
                                                    </div>
                                                </div>
                                                <div v-else>请先选择组织架构或员工</div>
                                            </a-card>
                                        </a-tab-pane>
                                    </a-tabs> -->
                                    <div style="text-align: right;margin: 10px 0" v-if="$checkPer(['permissionAssign'])">
                                        <a-button type="primary" @click="submit">提交</a-button>
                                    </div>
                                </a-row>
                            </div>
                        </a-col>
                    </a-row>
                </div>
            </a-card>
        </a-spin>
    </div>
</template>

<script lang="ts">
import api from "@/api/api";
import { getStorageUserInfo } from "@/utils";
import { Component, Vue } from "vue-property-decorator";
@Component({
    name: "permissionManagement",
    components: {},
})
export default class extends Vue {
    topLevel = "3a3bafbe4be36ca7fa9858b55687de4b";
    loading = false;
    pageReady = false;
    preType = 0;
    resourceIdS: string[] = [];
    replaceFields = { title: "name", key: "id", value: "id", children: "children" };
    treeData: any[] = [];
    memberList: any[] = [];
    search = "";
    selectMemberId = "";
    title = "总部";
    //权限数据
    workShopPermission: any[] = [];
    settingPermission: any[] = [];

    checkChange(e: any, value: any, parent?: any) {
        const id = value.id;
        const key = this.resourceIdS.indexOf(id);
        if (key >= 0) {
            this.resourceIdS.splice(key, 1);
        } else {
            this.resourceIdS.push(id);
        }
        if (parent && key<0) {
            const pid = parent.id;
            const pkey = this.resourceIdS.indexOf(pid);
            if (pkey >= 0) {
                //
            } else {
                this.resourceIdS.push(pid);
            }
        }
    }
    changeTab(tabIndex: any) {
        this.preType = tabIndex;
        if (this.preType === 0) {
            this.setOrganPer();
        } else {
            this.setUserPer();
        }
    }
    rightSideChangeTab(tabIndex: any) {
        console.log("rightSideChangeTab", tabIndex);
    }
    selectUser = {} as { id: string; name: string };
    memberClick(item: any) {
        this.selectUser = {
            id: item.userId,
            name: `${item.name}(${item.organizationName})`,
        };
        this.setUserPer();
    }
    selectNode = {} as { id: string; name: string };
    onSelect(selectedKeys: string, info: any) {
        this.selectNode = {
            id: info.node.dataRef.id,
            name: info.node.dataRef.name,
        };
        this.setOrganPer();
    }
    async setOrganPer() {
        this.title = this.selectNode.name;
        await this.getPermissionsOrganization(this.selectNode.id);
    }
    async setUserPer() {
        this.title = this.selectUser.name;
        if (this.selectUser.id) await this.getPermissionsUser(this.selectUser.id);
    }
    async mounted() {
        // 获取组织架构
        await this.getRootData();
        // 获取员工
        await this.getMemberData();
        //获取所有权限
        await this.getPermissionsAll();
        this.selectNode = {
            id: this.firstOrganizationId + "",
            name: this.treeData[0]?.name || "总部",
        };
        await this.setOrganPer();
        this.pageReady = true;
    }
    async getMemberData() {
        this.loading = true;
        try {
            // 获取员工
            const res = await api.getAccountList({
                organizationId: this.firstOrganizationId, //没有选中架构默认顶级id
                name: this.search,
            });
            this.memberList = res.data?.rows || [];
        } finally {
            this.loading = false;
        }
    }

    firstOrganizationId = "";
    async getRootData() {
        this.loading = true;
        try {
            let userInfo = getStorageUserInfo();
            if (userInfo && userInfo.type === "ORGAN") {
                // 机构端不需要传id
                const res = await api.getOrganizationList();
                this.treeData = res.data;
                this.firstOrganizationId = res.data[0].id;
            } else {
                const res = await api.getOrganizationList("3a3bafbe4be36ca7fa9858b55687de4b");
                this.firstOrganizationId = "3a3bafbe4be36ca7fa9858b55687de4b";
                this.treeData = res.data;
            }

            // 获取顶级架构
            // const res = await api.getOrganizationList(this.topLevel);
            // this.treeData = res.data;
        } finally {
            this.loading = false;
        }
    }
    // 获取架构对应权限
    async getPermissionsOrganization(id: string) {
        this.loading = true;
        try {
            const res = await api.getPermissionsById({ organizationId: id });
            this.resourceIdS = res.data.map((item) => item.id);
        } finally {
            this.loading = false;
        }
    }
    // 获取员工对应权限
    async getPermissionsUser(id: string) {
        this.loading = true;
        try {
            const res = await api.getPermissionsById({ userId: id });
            this.resourceIdS = res.data.map((item) => item.id);
        } finally {
            this.loading = false;
        }
    }
    // 获取所有权限
    async getPermissionsAll() {
        this.loading = true;
        try {
            const res = await api.getPermissionsById({});
            const { workPer, sysPer } = this.validPermissions(res.data);
            this.workShopPermission = workPer;
            console.info(workPer);
            //this.workShopPermission = res.data;
            this.settingPermission = sysPer;
        } finally {
            this.loading = false;
        }
    }

    /**
     * 格式权限 区分工作台和系统设置，输出树状结构
     *
     **/
    validPermissions(per: any[]) {
        let firstPer = per.filter((item) => item.parentId === 0);

        firstPer = firstPer.map((item) => {
            const children = per.filter((child) => child.parentId === item.id);
            return {
                ...item,
                children,
            };
        });
        //const workPer = firstPer.filter((item) => item.type === "GZT");
        const workPer = firstPer;
        const sysPer = firstPer.filter((item) => item.type === "XT");
        return { workPer, sysPer };
    }
    /**
     * 根据组织架构id 获取子架构id
     */
    getOrganizationChild(id: string, list: any[]) {
        const len = list.length;
        for (let i = 0; i < len; i++) {
            const item = list[i];
            if (item.id === id) {
                return item;
            } else {
                return this.getOrganizationChild(id, item.children);
            }
        }
        return null;
    }
    getOrganizationChildId(children: any[]) {
        const ids: string[] = [];
        const len = children.length;
        for (let i = 0; i < len; i++) {
            const item = children[i];
            ids.push(item.id);
            if (item.children && item.children.length > 0) {
                ids.concat(this.getOrganizationChildId(children[i].children));
            }
        }
        return ids;
    }
    async submit() {
        const data: any = {
            resourceIdS: this.resourceIdS,
        };
        if (this.preType === 0) {
            //组织架构
            const organizationObj = this.getOrganizationChild(this.selectNode.id, this.treeData);
            const organizationChildId = organizationObj ? this.getOrganizationChildId(organizationObj.children) : [];
            organizationChildId.push(this.selectNode.id);
            data.organizationIdS = {
                organizationId: this.selectNode.id,
                organizationParentId: organizationChildId,
            };
        } else {
            //员工
            data.pcUserId = this.selectUser.id;
        }
        this.loading = true;
        try {
            const res = await api.editPermissions(data);
            this.$message.success(res.msg);
        } finally {
            this.loading = false;
        }
    }
}
</script>
<style lang="scss">
@import "@/style/commonStyle.scss";
.permissions-container {
    padding: 20px;
    overflow: auto;
    .big-box {
        .ant-tree-node-content-wrapper {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: inline-block;
            max-width: 100%;
        }
        .left-side {
            margin-right: 20px;
            .table-box {
                margin-top: 20px;
                border: 1px solid #ccc;
                height: 600px;
                overflow: auto;
                &::-webkit-scrollbar {
                    display: none;
                }
                .item {
                    display: flex;
                    align-items: center;
                    padding: 10px;
                    .user-avatar {
                        flex-shrink: 0;
                    }
                    .user-info {
                        margin-left: 10px;
                        flex-grow: 1;
                        width: 10px;
                    }
                    .name {
                    }
                }
            }
        }
        .right-side {
            .list-box {
                border: 1px solid #ccc;
            }
            .item-box {
                padding: 15px;
                border-bottom: 1px solid #ccc;
                &:last-child {
                    border-bottom: none;
                }
            }
            .ant-checkbox-wrapper {
                margin-left: 0;
                margin-right: 8px;
            }
        }
    }
}
.active {
    background-color: $theme-color-fade;
}
</style>
